<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Category;
use App\Models\CompanyType;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\File\Exception\FileException;

class BaseController extends Controller
{
    protected $user;
    protected $modules;
    
    protected $item = 5;  //最大5级分类
    protected $upc = array();
    protected $nowCategory =array();
    protected $permerror;
    protected $noResource;
    
    public function __construct()
    {
        $this->middleware('auth');
        $this->user = Auth::user();
        $this->permerror = '抱歉，您没有相关操作权限！';
        $this->noResource = '抱歉，您请求的资源不存在';
//         $this->modules = array('employ'=>'就业指南','teaches'=>'充电加油','enterprise'=>'企业招聘','bbs'=>'青苜社区');
    }
    
    /**
     * 格式化分类参数
     * @param unknown $fourchild
     * @param unknown $subchild
     * @param unknown $child
     * @param unknown $type
     * @return Ambigous <number, unknown>
     */
    protected function getTypes($type,$child,$subchild,$fourchild)
    {
        if(isset($fourchild) && $fourchild !== 'undefined' && $fourchild != 'null' )
        {
            $cateid = $fourchild;
        }
        else
        {
            if((isset($subchild) && $subchild != 0 && $subchild !== 'undefined' && $subchild != 'null'))
            {
                $cateid = $subchild;
            }
            else
            {
                if(isset($child) && $child != 0 && $child !== 'undefined' && $child != 'null')
                {
                    $cateid = $child;
                }
                else
                {
                    if(isset($type) && $type !== 'undefined' && $type != 'null')
                    {
                        $cateid = $type;
                    }
                    else
                    {
                        $cateid = 0;
                    }
                }
            }
        }
        return $cateid;
    }
    
    /**
     * 根据子分类获取父分类
     * @param  $catid
     * @param  $pid
     * @return multitype:multitype: Ambigous <multitype:, unknown>
     */
    protected function getCate($catid,$pid,$app="employ")
    {
        if($pid>0)
        {
            $this->nowCategory[$this->item] = Category::where(array('pid'=>$pid,'app'=>$app))->get();  //当前平级分类
            $upcate = Category::where(array('cat_id'=>$pid,'app'=>$app))->first();   //获取父级分类
            if(!empty($upcate))
            {
                --$this->item;
                $this->upc[] =$upcate->cat_id;
                if ($upcate->pid > 0)
                {
                    $this->getCate($upcate->cat_id,$upcate->pid);
                }
            }
            $this->nowCategory = array_sort($this->nowCategory,function ($value){
                return $value;
            });
        }
        $this->upc[] = $catid;
        return array('list'=>$this->nowCategory,'id'=>$this->upc);
    }

    /**
     * 根据分类编号获取子分类
     * @param $cid
     */
    protected function getSubCateByCid( $cid, $app = 'organization' ) {
        $SubCat = Category::where(['pid' => $cid, 'app' => $app])->first();
        $hasSubCat = empty($SubCat) ? false : true;
        return $hasSubCat;
    }

    /**
     * xiadx
     * 获得指定分类同级的所有分类，以及该分类下的子分类
     * @param int $cat_id        分类编号
     * @param bool $is_samelv     是否显示同级分类，默认false
     * @param int   $ret_depath   返回的数组类型，1是一维数组，其它则为多维数组
     * @return array
     */
    protected function getCategoryTree($cat_id = 0, $is_samelv = false, $ret_depath = 1, $app ='organization')
    {
        static $depath = 0; //层级

        if ($is_samelv === true) {
            // 获得指定分类同级的所有分类
            if ($cat_id > 0) {
                $mod_cat = CompanyType::where(['id' => $cat_id])->first();
                $parent_id = $mod_cat->parent_id;
            } else {
                //顶级分类，获取所有分类->cached()
                $parent_id = 0;
            }
        } else {
            $parent_id = $cat_id; //获取指定分类下的子分类
        }

        $total = CompanyType::where(['parent_id' => $parent_id])->count();
        $cat_array =  array();
        if ($total > 0 || $parent_id == 0) {
            $data = CompanyType::where(['parent_id' => $parent_id])
                        ->get();
            //加一层
            ++$depath;
            foreach ($data AS $k => $row) {
                $cat_array[] = array(
                    'id' => $row->id,
                    'name' => $row->name,
                    'pid' => $row->parent_id,
                    'ordernum' => $row->sort,
                    'depath' => $depath,
                    'child_num' => 0
                );
                $cid = $row->id;
                $key = count($data) - 1;
                if ($ret_depath > 1) {

                    //递归，获取子分类
                    if ($child = $this->getCategoryTree($row->id, $is_samelv, $ret_depath)) {
                        $cat_array[$key]['child'] = $child;
                        $cat_array[$key]['child_num'] = count($child);
                    }
                } else {
                    //递归，获取子分类
                    if ($child = $this->getCategoryTree($cid, $is_samelv, $ret_depath)) {
                        $cat_array[$key]['child_num'] = 1;
                        foreach ($child as $sub) {
                            $cat_array[] = $sub;
                        }
                    }
                }
            }
            //减一层
            --$depath;
        }
        return $cat_array;
    }

    /**
     * 获取分类下拉菜单
     * @param int $selectid
     * @param bool $use_ext   是否使用mobile_catalog表，扩展分类信息
     * @return string
     */
    protected function getCategoryOptions($selectid = 0)
    {
        $cate_tree = $this->getCategoryTree(0, false, 1);
        $options = '<option value="0">----无----</option>';
        foreach ($cate_tree as $cat) {
//            if ($cat['disabled'] == 1) continue; //该分类被禁用
            if ($selectid > 0 && $selectid == $cat['id']) {
                $selected = 'selected="true"';
            } else {
                $selected = '';
            }
            if ($cat['depath'] == 1) {
                $options .= sprintf('<option value="%d" %s>├ %s</option>', $cat['id'], $selected, $cat['name']);
            } else {
                $options .= sprintf('<option value="%d" %s>%s├ %s</option>', $cat['id'], $selected,
                    str_repeat('&nbsp;', $cat['depath'] * 2), $cat['name']);
            }
        }
        return $options;
    }

    public function formatJson($status='200',$msg='没有更多数据',$data=array(),$redirectUrl = '')
    {
        $result = array(
            'status'        => $status,
            'msg'           => $msg,
            'data'          => $data,
            'redirectUrl'   => $redirectUrl
        );
        return Response::json($result);
    }
    
    public function getSubCategory($catid)
    {
        $categorys = DB::table('category')->where('pid',$catid)->lists('cat_id');
        if(!empty($categorys))
        {
            $category = DB::table('category')->whereIn('pid',$categorys)->lists('cat_id');
            if(!empty($category))
            {
                $result = array_unique(array_merge($categorys,$category));
                return $result;
            }
            return $categorys;
        }
        return array($catid);
    }
    
    /**
     * 创建文件夹 
     */
    protected function qmMakeDir($directory)
    {
        if (!is_dir($directory)) {
            if (false === @mkdir($directory, 0777, true) && !is_dir($directory)) {
                throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
            }
        } elseif (!is_writable($directory)) {
            throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
        }
    }
    
    /*
    protected function office2swf($docurl,$docname,$docpath)
    {
        
        if(file_exists(public_path($docurl)))
         {
         $pdf_directory = public_path($docpath.'pdf');
         $this->qmMakeDir($pdf_directory);
    
         $pdfurl = $pdf_directory.$docname.'.pdf';
         $command = 'java -jar /usr/local/wenku/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar '
         .public_path($docurl).' '.$pdfurl;
         exec($command);
         if(file_exists(public_path($pdfurl)))
         {
         $swf_directory = public_path($docpath.'swf');
         $this->qmMakeDir($swf_directory);
         $swfurl = $swf_directory.$docname.'.swf';
         $swfCommand = "pdf2swf -o ".$swfurl
         ." -T-z-t-f ".$pdfurl." -s languagedir=/usr/share/xpdf/ -s flashversion=9";
         exec($swfCommand);
         return  array('pdfurl'=>$docpath.'pdf'.$docname.'.pdf','swfurl'=>$docpath.'swf'.$docname.'.swf');
         }
         }
    }*/
}

